var _locationObj = window.location;
var _host = _locationObj.host;
var _wroot = _locationObj.host + "/";

$(document).ready(function() {
    $('input:button, input:submit, button').button();
    
    $('#login').dialog({ autoOpen:false, width:450,
        buttons: [{
                    id:"btn_login",
                    text: "Login",
                    click: function() {
                            Authenticate_User($('#btn_login'));
                    }
                },{
                    id:"btn_cancel",
                    text: "Cancel",
                    click: function() {
                            $(this).dialog("close");
                    }
                }]
    }); 
    
    $('#btn_logout').click(Logout);
    
    $('#btn_open_options').click(function () {Open_Map_Options()});
    $('#map_canvas').click(function () {Close_Map_Options();});
});

function Open_Map_Options(){
    $('#btn_open_options').fadeOut('fast', function () {$('#map_options').fadeIn('slow');})
}

function Close_Map_Options(){
    $('#map_options').fadeOut('fast', function () {$('#btn_open_options').fadeIn('slow');});
}

function Authenticate_User(button){
    var authenticated = false;
    var original_text = $('span',button).text();
    $('span',button).text('Loadding...');
    $(button).attr('disabled', 'true');
    $.ajax({
        type: "POST",
        url: "/php/controller/login.php",
        data:$('#frm_login').serialize(),
        success: function(data){
            //alert(data);
            authenticated = data;
            switch(authenticated){
                case "0":
                    $('#form_message').attr('class', '');
                    $('#form_message').css('display', 'none');
                    $('#login').dialog('close');
                    window.location = _locationObj;
                    break;
                case "1":
                    $('#form_message').attr('class', 'form_message_error');
                    $('#form_message').html('Username invalid');
                    $('#form_message').css('display', 'block');
                    break;
                case "2":
                    $('#form_message').attr('class', 'form_message_error');
                    $('#form_message').html('Password invalid');
                    $('#form_message').css('display', 'block');
                    break;
            }
            $('span',button).text(original_text);
            $(button).removeAttr('disabled');
        }
    });    
}

function Logout(){
    $.ajax({
        type: "POST",
        url: "php/controller/logout.php",
        success: function(){
            window.location = _locationObj;
        }
    });
}

